<?php

namespace app\common\util;

use app\common\model\trResource;
use app\common\model\trSystemSet;
use app\saas\model\trSetting;
use Qcloud\Cos\Client;

/**
 * 腾讯云上传
 */
class CosUploads
{
    public $savePath = 'image/';
    public $root;
    public $rootUrl;
    public $cosConfig;
    public $cosClientObject;

    public function __construct()
    {
        header("Content-Type: text/html; charset=utf-8");
        $this->root = "car_tp5/" . config('upload.basePath') . request()->mallData["id"] . "/";
        $this->rootUrl = "/car_tp5/" . config('upload.uploadBase') . request()->mallData["id"] . "/";
    }

    public function createCosObject(){
        if (empty($this->cosClientObject)) {
            if(request()->module() == "saas") { // saas端
                $this->cosConfig = trSetting::getFields("secret_id,secret_key,region,bucket");
            }else{
                $this->cosConfig = trSystemSet::getValue("tcConfig");
            }
            if (empty($this->cosConfig["secretId"]) || empty($this->cosConfig["secretKey"]) || empty($this->cosConfig["region"]) || empty($this->cosConfig["bucket"])) {
                throw new \Exception("未配置腾讯云信息，无法使用", 1);
            }
            $this->cosClientObject = new Client([
                'region' => $this->cosConfig["region"], #地域，如ap-guangzhou,ap-beijing-1
                'credentials' => array(
                    'secretId' => $this->cosConfig["secretId"],
                    'secretKey' => $this->cosConfig["secretKey"],
                ),
            ]);
        }
        return $this->cosClientObject;
    }

    public function ueditor()
    {
        $result = config('upload.ueditor');
        return $result;
    }

    //上传图片
    public function upImage($fieldName, $validate, $userId)
    {
        $file = request()->file($fieldName);
        if(empty($file)){
            return array('msg' => "没有上传文件，请检查key");
        }
        if(isset($validate["sizeWH"])){
            $size = getimagesize($file->getInfo("tmp_name"));
            if($size[0] != $validate["sizeWH"][0]){
                return array('msg' => "图片的宽度必须为{$validate["sizeWH"][0]}");
            }
            if($size[1] != $validate["sizeWH"][1]){
                return array('msg' => "图片的长度必须为{$validate["sizeWH"][1]}");
            }
            unset($validate["sizeWH"]);
        }
        try{
            $file->validate($validate);
            if(!request()->server("IS_SCF")) { // 云函数 不需要校验
                // 检测合法性
                if (!$file->isValid()) {
                    return array('msg' => "上传文件有误");
                }
            }
            // 验证上传
            if (!$file->check()) {
                return array('msg' => $file->getError());
            }
            $result = $this->createCosObject()->putObject(array(
                'Bucket' => $this->cosConfig["bucket"],
                'Key' => $this->root . $this->savePath . date('Y-m') . '/' . date('d') . '/'.
                    md5(time()) . "." . pathinfo($file->getInfo("name"), PATHINFO_EXTENSION),
                'Body' => fopen($file->getInfo("tmp_name"), 'rb')
            ));
            $address = $result->get("ObjectURL");
        } catch (\Exception $e) {
            return array('msg' => $e->getMessage().var_export($this->cosConfig, true));
        }

        if (!empty($address)) {
            $info = pathinfo($address);
            $data = array(
                'id' => $info["filename"],
                'url' => $address,
                'title' => $info["basename"],
                'type' => '.' . $info["extension"],
                'state' => "SUCCESS"
            );
            //存储图片到数据库
            trResource::add(array(
                'id' => $info["filename"],
                'name' => $data['title'],
                'location' => explode('/', request()->path())[0],
                'url' => $data['url'],
                "user_id" => $userId,
                'time' => time()
            ));
            $data['url'] = tome_dia($data['url']);
        } else {
            return array('msg' => "上传错误，请检查腾讯云cos存储");
        }
        return $data;
    }

    /**
     * @param $fieldName
     * @param $validate
     * @param int $userId
     * @return array
     * 文件上传
     */
    public function upFile($fieldName, $validate, $userId = 0)
    {
        $file = request()->file($fieldName);
        if(empty($file)){
            return array('msg' => "没有上传文件，请检查key");
        }
        try{
            $file->validate($validate);
            if(!request()->server("IS_SCF")) { // 云函数 不需要校验
                // 检测合法性
                if (!$file->isValid()) {
                    return array('msg' => "上传文件有误");
                }
            }
            // 验证上传
            if (!$file->check()) {
                return array('msg' => $file->getError());
            }

            $result = $this->createCosObject()->putObject(array(
                'Bucket' => $this->cosConfig["bucket"],
                'Key' => $this->root . $this->savePath . date('Y-m') . '/' . date('d') . '/' . mt_rand(1, 200) ."_". $file->getInfo("name"),
                'Body' => fopen($file->getInfo("tmp_name"), 'rb')
            ));
            $address = $result->get("ObjectURL");
        } catch (\Exception $e) {
            return array('msg' => $e->getMessage());
        }
        if(!empty($address)) {
            $info = pathinfo($address);
            $data = array(
                'id' => $info["filename"],
                'url' => $address,
                'title' => $info["basename"],
                'state' => "SUCCESS"
            );
        }else{
            $data = array(
                'state' => 'ERROR',
                'msg' => '上传错误，请检查腾讯云cos存储',
            );
        }
        return $data;
    }

    /**
     * 数据库列出图片
     */
    public function fileLists($listSize, $get){

        /* 获取参数 */
        $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
        $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;

        /* 获取文件列表 */
        $file = trResource::where('type', 'admin')->order('time', 'desc')
            ->field('url,time')
            ->paginate(array('list_rows'=>$size,'page'=>$start/$size));
        $data = $file->items();
        if (!count($data)) {
            return json_encode(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => $file->total()
            ));
        }
        $list = [];
        foreach ($data as $item){
            $list[] = ['url' => request()->domain() . __PUBLIC__ . $item['url'],'mtime' => $item['time']];
        }

        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => $file->total()
        ));

        return $result;
    }
}